import store from '@/store'
let baseConfig = {
	baseUrl: "/api",
	version: 'v1',
	data: {},
	method: "get",
	autoError: true,
	loading: true,
	from: 'wx',
	header: {
		'content-type': 'application/x-www-form-urlencoded',
		'Accept': 'application/json',
		"from": 'wx',
	},
}

const service = (data) => {
	let config = JSON.parse(JSON.stringify(baseConfig))
	for (let key in data) {
		config[key] = data[key]
	}
	if (config.loading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	config.header.Authorization = "Bearer " + store.state.$token
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.baseUrl + '/' + config.version + '/' + config.url,
			data: config.data,
			method: config.method,
			header: config.header,
			success: (res) => {
				if (res.data.code == 1001) {
					uni.showModal({
						title: '提示',
						content: '登录失效，是否重新登录',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								});
							} else if (res.cancel) {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});
					reject(res);
				} else {
					if (config.autoError) {
						if (res.data.status != 1 && config.loading) {
							uni.showToast({
								title: res.message,
								duration: 2000,
								icon: "none"
							});
						} else {
							resolve(res.data.data)
						}
					} else {
						resolve(res.data)
					}
				}
			},
			fail: (error) => {
				console.error(error)
				if (config.loading) {
					uni.showToast({
						title: '请求失败',
						duration: 2000,
						icon: "none"
					});
				}
				reject(error);
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	})
}
export default service
